#include "List.h"

//创建一块头结点（哨兵位结点，存储数据无效）
LTNode* LTBuyNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	newnode->data = x;
	newnode->next = newnode->prev = newnode;

	return newnode;

}

/*

//初始化链表
void LTInit(LTNode** pphead)
{
	//创建一个头结点（哨兵位）
	*pphead = LTBuyNode(-1); //无效数据
}

*/


//初始化优化
LTNode* LTInit()    //通过返回值传递，接受初始化方法的返回值（哨兵位结点的指针）
{
	LTNode* phead = LTBuyNode(-1);
	return phead;
}




//打印链表
void LTPrint(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}


//尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead); 

	LTNode* newnode = LTBuyNode(x); 
	newnode->next = phead;
	newnode->prev = phead->prev;

	phead->prev->next = newnode; 
	phead->prev = newnode;
}

//头插
void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* newnode = LTBuyNode(x);
	 
	newnode->prev = phead;
	newnode->next = phead->next;

	phead->next->prev = newnode;
	phead->next = newnode;
}

//判断链表是否为空
bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead; //链表为空的情况
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}


//指定位置之后插入数据
void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newnode = LTBuyNode(x);
	
	//pos newnode pos->next
	newnode->prev = pos;
	newnode->next = pos->next;

	pos->next->prev = newnode;
	pos->next = newnode;
}





//尾删
void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead)); //链表不为空

	//phead  prev(del->prev)  del(phead->prev) 
	LTNode* del = phead->prev;
	LTNode* prev = del->prev;

	phead->prev = prev;
	prev->next = phead;

	free(del);
	del = NULL;
}


//头删
void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	LTNode* del = phead->next;
	phead->next = del->next;
	del->next->prev = phead;

	free(del);
	del = NULL;

}


//在指定位置删除结点
void LTErase(LTNode* pos)
{
	assert(pos);

	// pos->prev  pos   pos->next
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	

	free(pos);
	pos = NULL;
}

/*


//销毁链表
void LTDesTroy(LTNode** pphead)
{
	assert(pphead && *pphead); //链表和哨兵位都不能为空
	LTNode* pcur = (*pphead)->next;
	while (pcur!=*pphead)
	{
		LTNode* Next = pcur->next;
		free(pcur);
		pcur = Next;
	}
	//销毁哨兵位结点
	free(*pphead);
	*pphead = NULL;
	pcur = NULL;
	
}

*/


//销毁链表优化
void LTDesTroy2(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* Next = pcur->next;
		free(pcur);
		pcur = Next;
	}
	free(phead);
	phead = pcur = NULL;
}
